import requests
import re

# startpag = int(input('请输入起始页：'))
# endpag = int(input('请输入结束页：'))
n = 0
for pagindex in range(1,11):
    base_url = 'https://nj.58.com/chuzu/pn%d/?PGTID=0d3090a7-000a-ca3c-b34d-fb348e9bed61&ClickID=2' % (pagindex)
    # 执行请求信息
    req = requests.get(base_url)
    try:
        # 获取响应内容
        html = req.content.decode('utf-8')
        # 正则表达式匹配图片，标题，户型，价格
        pat = 'lazy_src="(.*?)".*?<span class="picNum">.*?</span>.*?<h2>.*?<a href=".*?".*?class="strongbox".*?>(.*?)</a>.*?</h2>.*?<p class="room strongbox">(.*?)</p>.*?<b class="strongbox">(.*?)</b>(.*?)</div>'
        dlist = re.findall(pat,html,re.S)
        for d in dlist:
            print('图片地址：' + d[0] + '\t'+ '标题：' + str(re.sub('\s','',d[1])) + '\t' + '户型：' + str(re.sub('\s|&nbsp;','',d[2])) + '\t'+ '价格：' + d[3]+d[4])
        n += len(dlist)
        print('第{}页信息爬取完毕'.format(pagindex))
        print('共爬取{}条出租信息'.format(n))
    except Exception as e:
        if hasattr(e,'reason'):
            print(e.reason)

        if hasattr(e,'code'):
            print(e.code)
